#!/bin/bash

source /home/shell/util.sh

pid=`ps aux|grep geth|grep -v grep|awk '{print $2}'`;
if [ -n "${pid}" ]; then
    kill -9 $pid
fi

read -p $'请选择网络类型：\n1. main;\n2. rinkeby网络;\n3. ropsten网络\n4. dev;\n[4. dev default]:' net_type
net_type=${net_type:-"4"};

read -p "指定数据目录[/home/eth/node1]：" data_dir
data_dir=${data_dir:-"/home/eth/node1"};

read -p $'请选择同步类型：\n1. fast;\n2. full;\n3. light;\n[1. fast default]:' syncmode_num
syncmode_num=${syncmode_num:-"1"};

if [ ! -d "/usr/local/geth" ]; then
    download /usr/local/geth.tar.gz https://gethstore.blob.core.windows.net/builds/geth-linux-amd64-1.10.4-aa637fd3.tar.gz
    tar -xf /usr/local/geth.tar.gz -C /usr/local/
    mv /usr/local/geth-linux-amd64* /usr/local/geth
    rm -rf /usr/local/geth.tar.gz

tee /etc/profile.d/eth.sh<<EOF
export PATH="/usr/local/geth:\$PATH"
EOF

    source /etc/profile.d/eth.sh
fi

if [ ! -d "${data_dir}" ]; then
    mkdir -p ${data_dir}
fi

geth --datadir ${data_dir} init /home/shell/support/ethereum/genesis.json


case "${net_type}" in
    1)
        printInfo "使用main网！"
        main_net=''
    ;;
    2)
        printInfo "使用rinkeby网！"
        test_net='--rinkeby'
    ;;
    3)
        printInfo "使用ropsten网！"
        test_net='--ropsten'
    ;;
    4)
        printInfo "使用dev网！"
        dev_net='--dev --dev.period 1'
    ;;
    *)
        printInfo "非法输入，请检查脚本。"
        exit;
    ;;
esac

case "${syncmode_num}" in
    1)
        syncmode='--syncmode fast'
        break;
    ;;
    2)
        syncmode='--syncmode full'
        break;
    ;;
    3)
        syncmode='--syncmode light'
        break;
    ;;
    *)
        printInfo "非法输入，请检查脚本。"
        exit;
    ;;
esac

rm -rf ${data_dir}/geth.toml

# 下载星火计划
download ${data_dir}/static-nodes.json https://upyun-assets.ethfans.org/uploads/doc/file/b0c5266be42f43f1baf7207c432bede6.json?_upd=static-nodes.json

geth --identity "mychainbyshell" --datadir "${data_dir}" --networkid "6554" --rpc --rpccorsdomain "*"--nodiscover --port 30303 --rpcport 8545 --allow-insecure-unlock \
--rpcapi "eth,net,web3,admin,miner,personal" --rpcaddr "0.0.0.0" --rpc.allow-unprotected-txs --nousb ${main_net} ${test_net} ${dev_net} ${syncmode} dumpconfig > ${data_dir}/geth.toml

# nohup geth --config ${data_dir}/geth.toml >> /var/log/webapps/ethereum/log.log 2>&1 &

firewall-addport 8545
firewall-addport 30303

# 创建服务
bash /home/shell/serviced-install.sh<<EOF
1
2
10
/var/log/webapps/ethereum
geth
/usr/local/geth/geth --config ${data_dir}/geth.toml




EOF

printInfo "=============ethereum=============";
echo "日志：/var/log/webapps/ethereum/geth-info.log"
echo "rpcport:8545"
echo "port:30303"
echo "rpcapi:eth,net,web3,admin,miner,personal"
echo "datadir:${data_dir}"
echo "networkid:6554"
echo -e "`geth version`"
printInfo "=============ethereum=============";